#include <iostream>
#include <memory>
#include <string>

#include "absl/flags/flag.h"
#include "absl/flags/parse.h"

#include <grpcpp/grpcpp.h>
#include "greet.grpc.pb.h"

ABSL_FLAG(std::string, target, "localhost:8888", "Server address");

class GreetClient {
public:
    GreetClient(std::shared_ptr<grpc::Channel> channel) 
        : _stub(greeting::Greeter::NewStub(channel)) {}
        
    std::string SayHello(const std::string& user) {
        greeting::HelloRequest request;
        request.set_name(user);

        greeting::HelloReply reply;
        grpc::ClientContext  context;
        grpc::Status status = _stub->SayHello(&context, request, &reply);
        
        if (status.ok()) {
            return reply.message();
        } else {
            std::cout << status.error_code() << ": " << status.error_message() << std::endl;
            return "RPC faild!";
        }
    }
private:
    std::unique_ptr<greeting::Greeter::Stub> _stub;
};
int main(int argc, char **argv) {
    absl::ParseCommandLine(argc, argv);
    std::string server_addr = absl::GetFlag(FLAGS_target);

    GreetClient greeter(grpc::CreateChannel(server_addr, grpc::InsecureChannelCredentials()));
    
    std::string user("zhangsan");
    std::string reply = greeter.SayHello(user);
    std::cout << "Greeter received: " << reply << std::endl;
    return 0;
}